/*
 * C/C++ Lessons Program
 * 
 * Copyright (c) 2012 Ken Zhang (cpp.china@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 */


#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>

#define SIG_CHILD_QUIT	SIGTERM

int main_proc(pid_t child_pid)
{
	int ch = 0;
	do {
		puts("Main Proc: press 'q' to exit.");
		sleep(3);
		ch = fgetc(stdin);
		printf("  '%c'(%d) pressed.\n", ch, ch);
	} while (ch != 'q');

	puts("Main Proc: send termination signal to child proc.");
	kill(child_pid, SIG_CHILD_QUIT);

	puts("Main Proc: wait for child to exit...");
	wait(NULL);

	puts("Finished.");
	return 0;
}

void child_proc_signal_handler(int sig)
{
	switch (sig) {
	case SIG_CHILD_QUIT:
		puts("Child Proc: caught SIGNAL to stop.");
		exit(1);
		break;
	default:
		break;
	}
}

int child_proc()
{
	puts("Child Proc: child process started.");
	signal(SIG_CHILD_QUIT, child_proc_signal_handler);
	char ch = 'a';
	while (1) {
		printf("Child Proc: %c\n", ch);
		if (ch++ == 'z') ch = 'a';
		sleep(1);
	}
	exit(0);
}

int main()
{
	pid_t pid;

	switch (pid = fork()) {
	case -1:
		perror("Fork failed");
		break;
	case 0:
		child_proc();
		break;
	default:
		main_proc(pid);
		break;
	}

	return 0;
}

